<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2018/6/18
 * Time: 19:01
 */

namespace app\common\model;

use \Firebase\JWT\JWT;
use think\Config;

class Jwt_base{
    public $jwt_key;

    public $token;

    public function __construct()
    {
        Config::load(APP_PATH . 'coomon/config.php');

        //获取默认key值
        $this->jwt_key = Config::get('jwt_key');

//        $this->token = array(
//            "username"=>'default',
//            "password"=>'',
//            "login_time"=>gettime(),
//        );

        $this->token = [
            'iss' => 'http://www.topsydy.com', //签发者
            'aud' => 'http://www.topsydy.com', //jwt所面向的用户
            'iat' => time(), //签发时间
            'nbf' => time(), //在什么时间之后该jwt才可用
            'exp' => time() + 10, //过期时间-10min
            'data' => [
                'userid' => 1,
                'username' => 'user'
            ]
        ];
    }

    //jwt encodeing
    public function encode($userid,$username){
        $this->token["data"]["userid"] = $userid;
        $this->token["data"]["username"] = $username;
//        $token = array(
//            "asd" => "http://example.org",
//            "aud" => "http://example.com",
//            "iat" => 1356999524,
//            "nbf" => 1357000000
//        );

        /**
         * IMPORTANT:
         * You must specify supported algorithms for your application. See
         * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
         * for a list of spec-compliant algorithms.
         */
        $jwt = JWT::encode($this->token, $this->jwt_key);

        return $jwt;
    }

    public function decode($jwt ,$alg=array('HS256')){

        //$decoded_array = (array) $decoded;
       // print_r($decoded);
        try {
            JWT::$leeway = 60;
            $decoded = JWT::decode($jwt, $this->jwt_key, $alg);
            $arr = (array)$decoded;
        } catch(Exception $e) {
            $arr = 'Token验证失败,请重新登录';
        }

        return $arr;
    }
}
